package com.mmall.common;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * guava 缓存工具类
 * Created by qezhhnjy on 2017/9/25-15:14.
 */
public class TokenCache {

    public static final String TOKEN_PREFIEX = "token_";

    private static Logger logger = LoggerFactory.getLogger(TokenCache.class);

    //这段代码为guava式调用链声明一个本地缓存,分别设置了缓存的初始容量,最大容量(超过会采用LRU算法处理),缓存时间.
    private static LoadingCache<String, String> localCache = CacheBuilder.newBuilder().
            initialCapacity(1000).maximumSize(10000).expireAfterAccess(12, TimeUnit.HOURS).
            build(new CacheLoader<String, String>() {
                @Override
                //默认的数据加载实现,当调用get取值时,如果key没有对应的值,就调用这个方法进行加载.
                public String load(String s) throws Exception {
                    return null;
                }
            });

    public static void setKey(String key, String value) {
        localCache.put(key, value);
    }

    public static String getKey(String key) {
        try {
            return localCache.get(key);
        } catch (Exception e) {
            logger.error("localCache get error", e);
        }
        return null;
    }
}
